#include <Arduino.h>
#include <Servo.h>
#include <Wire.h> //Arduino内置IIC
#include <ESP8266WiFi.h> 
#include "motion.h"
#include "battery.h"
#include "screen.h"
#include "wifi.h"
#include "server.h"
#include "fetchinfo.h"
#include "state.h"
#include "serial.h"
#include <ESPAsyncWebServer.h>
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>BUTTON
#define BUTTON_PIN 2
#define BUTTON_PIN_2 15
bool Button_Pressed = false;
const unsigned long DebounceDelay = 50; //两次按下不能短于 50ms
bool Button_Pressed_2 = false;
unsigned long LastPressTime = 0; // 记录上次按下的时间
unsigned long LastPressTime_2 = 0;
void IRAM_ATTR HandleButtonPress() { //ICACHE_RAM_ATTR函数强制存到RAM里
  return;
}


void setup() {
  Serial.begin(115200);
  ScreenInit();
  MotionInit();
  SPIFFS.begin();

  pinMode(BUTTON_PIN, INPUT_PULLUP);
  attachInterrupt(BUTTON_PIN, HandleButtonPress, FALLING);
  pinMode(BUTTON_PIN_2, INPUT_PULLUP);
  attachInterrupt(BUTTON_PIN_2, HandleButtonPress, RISING);
  StartWifiAP();
  Serial.println("HotSpot Started");
  Serial.println("HotSpot Addr: " + WiFi.softAPIP().toString());
  LoadWifiConfig();
  // server.on("/",HTTP_GET,[](AsyncWebServerRequest *request){
  //   request->send(200, "text/plain", "ello");
  // });
  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("Locacl Ip: ");
    Serial.println(WiFi.localIP());  // 打印本机IP
    TimeClient.begin();
    TimeClient.update();
  }

  HTTPServerResponseConfig();
  
  delay(2000);
  Moe();
  delay(1000);
  ScreenClear();
  Dead();
  delay(1000);
  ScreenClear();
  Pig();
  delay(1000);
  ScreenClear();
  Emm();
  delay(1000);
  ScreenClear();
  ShowWiFi(WiFi.softAPIP().toString(),WiFi.localIP().toString());
  delay(2000);
  
}

void loop() {
  GetAverageAdcVoltage();

  String inString="";
  while(Serial.available()>0){
    inString += char(Serial.read());
    delay(10);      // 延时函数用于等待字符完全进入缓冲区
  }
  HandleSerialMessage(inString);

  if(EmojiState != PrevEmojiState) {
    ScreenClear();
    PrevEmojiState = EmojiState;
  }
  if(FreeState) {
    delay(3000);
    ActionState = random(1,10);
  }
  switch(ActionState) {
    case ACTION_STATE_FRONT:
      Front();
      break;
    case ACTION_STATE_BACK:
      Back();
      break;
    case ACTION_STATE_LEFT:
      Left();
      break;
    case ACTION_STATE_RIGHT:
      Right();
      break;
    case ACTION_STATE_SITDOWN:
      SitDown();
      break;
    case ACTION_STATE_LAYDOWN:
      LieDown();
      break;
  }
  ActionState = ACTION_STATE_NONE;
  switch(EmojiState) {
    case EMOJI_STATE_HAPPY:
    Moe();
    break;
    case EMOJI_STATE_DEAD:
    Dead();
    break;
    case EMOJI_STATE_SAD:
    Pig();
    break;
    case EMOJI_STATE_ANGRY:
    Emm();
    break;
  }
}